<?php

namespace App\Http\Controllers;


use App\Events\OrderPaid;
use App\Exceptions\InvalidRequestException;
use App\Http\Requests\OrderRequest;
use App\Models\Order;
use App\Models\UserAddress;
use App\Services\CartServices;
use App\Services\OrderService;
use Illuminate\Http\Request;

class OrdersController extends Controller
{
    
    public function store(OrderRequest $request,OrderService $orderService){
        $user = $request->user();
        $address = UserAddress::find($request->input("address_id"));
        return $orderService->store($user,$address,$request->input("remark"), $request->input('items'));

    }

    public function index(Request $request){
        $order = Order::query()
        //使用with方法避免n+1问题
            ->with(["items.product","items.productSku"])
            ->where("user_id",$request->user()->id)
            ->orderBy("created_at","desc")
            ->paginate();
        return view("orders.index",['orders' => $order]);
    }

    public function show(Order $order, Request $request)
    {
        $this->authorize("own",$order);
        return view('orders.show', ['order' => $order->load(['items.productSku', 'items.product'])]);
    }

    protected function afterPaid(Order $order){
        event(new OrderPaid($order));
    }
}
